﻿using System;
using System.Text;
using log4net;

namespace HashFoo.MigratorFoo
{
    public class MigrationGenerator : IMigrationGenerator
    {
        private readonly ILog _log = log4net.LogManager.GetLogger("MigratorFoo");

        public NHibernate.Cfg.Configuration Config { get; set; }
        public IMigrationInverter MigrationInverter { get; set; }

        public MigrationGenerator()
        {
            this.MigrationInverter = new SimpleMigrationInverter();
        }

        public MigrationScript GenerateMigration()
        {
            if (Config == null)
            {
                _log.Error("No configuration set");
                throw new InvalidOperationException("No database configurations found.");
            }

            var schemaUpdater = new NHibernate.Tool.hbm2ddl.SchemaUpdate(Config);
            var schemaBuilder = new StringBuilder();
            var downBuilder = new StringBuilder();
            schemaUpdater.Execute(
                s =>
                {
                    _log.Info("Up Script Part: " + Environment.NewLine + s);
                    schemaBuilder.Append(s + ";");

                    var downscript = this.MigrationInverter.InvertCommand(s);
                    _log.Info("Down Script Part: " + Environment.NewLine + downscript);
                    downBuilder.Insert(0, downscript);
                }, false);

            var scripts = new MigrationScript
                              {
                                  UpScript = schemaBuilder.ToString(),
                                  DownScript = downBuilder.ToString()
                              };

            return scripts;
        }
    }
}
